<?php

namespace app\services;

use app\payment\PayFactory;
use plugin\admin\app\model\Config;
use plugin\admin\app\model\ConfigGroup;
use plugin\admin\app\model\Option;
use Yansongda\Pay\Pay;

class ConfigService
{
    public static function get($key)
    {
        if (is_array($key)) {
            $configs = Config::whereIn('key', $key)->get()->toArray();

            return array_combine(
                array_column($configs, 'key'),
                array_column($configs, 'value')
            );
        } else {
            $config = Config::where('key', $key)->first();
            return $config['value'] ?? '';
        }
    }

    public static function getByGroup($groupKey)
    {
        $group = ConfigGroup::where('key', $groupKey)->first();

        $configs = Config::where('group_id', $group['id'])->get()->toArray();

        return array_combine(
            array_column($configs, 'key'),
            array_column($configs, 'value')
        );
    }

    public static function getSmsConfig()
    {
        $smsConfig = ConfigService::getByGroup('sms');

        foreach ($smsConfig as $key=>$value) {
            if (empty($value)) {
                throw new \Exception('阿里云短信配置不正确,请在后台->设置->配置中心->阿里云短信配置处进行配置');
            }
        }

        $config = [
            // HTTP 请求的超时时间（秒）
            'timeout' => 5.0,

            // 默认发送配置
            'default' => [
                // 网关调用策略，默认：顺序调用
                'strategy' => \Overtrue\EasySms\Strategies\OrderStrategy::class,

                // 默认可用的发送网关
                'gateways' => [
                    'aliyun',
                ],
            ],
            // 可用的网关配置
            'gateways' => [
                'errorlog' => [
                    'file' => '/tmp/easy-sms.log',
                ],
                'aliyun' => [
                    'access_key_id' => $smsConfig['sms_aliyun_access_key_id'],
                    'access_key_secret' => $smsConfig['sms_aliyun_access_key_secret'],
                    'sign_name' => $smsConfig['sms_aliyun_sign_name'],
                ],
                //...
            ],
        ];

        return $config;
    }

    public static function getPaymentConfig($payWayConfigCheck, $payWayTypeCheck = null)
    {
        $wechatConfig = self::getByGroup('wechat_pay');

        $mpAppId = self::get('mp_app_id');
        $miniAppId = self::get('mini_app_id');
        $appId = self::get('app_id');

        if ($payWayTypeCheck) {
            switch ($payWayTypeCheck) {
                case 'mp':
                case 'scan':
                    if (empty($mpAppId)) {
                        throw new \Exception('请在后台配置公众号支付, 后台->支付->微信支付->微信公众号支付');
                    }
                    break;
                case 'mini':
                    if (empty($miniAppId)) {
                        throw new \Exception('请在后台配置公众号支付, 后台->支付->微信支付->微信小程序支付');
                    }
                    break;
                case 'app':
                    if (empty($appId)) {
                        throw new \Exception('请在后台配置公众号支付, 后台->支付->微信支付->微信app支付');
                    }
                    break;
            }
        }

        if ($payWayConfigCheck == PayFactory::WECHAT) {
            foreach ($wechatConfig as $value) {
                if (empty($value)) {
                    throw new \Exception('请在后台配置微信支付, 后台->支付->微信支付');
                }
            }


            if (!file_exists(admin_public_path($wechatConfig['mch_secret_cert']))) {
                throw new \Exception('微信商户私钥配置不正确');
            }

            if (!file_exists(admin_public_path($wechatConfig['mch_public_cert_path']))) {
                throw new \Exception('微信商户公钥配置不正确');
            }

            $wechatConfig = [
                'mch_id' => $wechatConfig['mch_id'],
                'mch_secret_key_v2' => $wechatConfig['mch_secret_key_v2'],
                // 必填-商户秘钥
                'mch_secret_key' => $wechatConfig['mch_secret_key'],
                // 必填-商户私钥 字符串或路径
                'mch_secret_cert' => admin_public_path($wechatConfig['mch_secret_cert']),
                // 必填-商户公钥证书路径
                'mch_public_cert_path' => admin_public_path($wechatConfig['mch_public_cert_path']),
                // 必填
                'notify_url' => getenv('APP_URL') . '/api/wechat/notify',
                // 选填-公众号 的 app_id
                'mp_app_id' => $mpAppId,
                // 选填-小程序 的 app_id
                'mini_app_id' => $miniAppId,
                // 选填-app 的 app_id
                'app_id' => $appId,
                // 选填-合单 app_id
                'combine_app_id' => '',
                // 选填-合单商户号
                'combine_mch_id' => '',
                // 选填-服务商模式下，子公众号 的 app_id
                'sub_mp_app_id' => '',
                // 选填-服务商模式下，子 app 的 app_id
                'sub_app_id' => '',
                // 选填-服务商模式下，子小程序 的 app_id
                'sub_mini_app_id' => '',
                // 选填-服务商模式下，子商户id
                'sub_mch_id' => '',
                // 选填-默认为正常模式。可选为： MODE_NORMAL, MODE_SERVICE
                'mode' => Pay::MODE_NORMAL,
                'wechat_public_cert_path' => [
                    $wechatConfig['public_key'] => admin_public_path($wechatConfig['public_key_file']),
                ],
                'log' => [
                    'file' => runtime_path().'/logs/wechat_pay.log',
                    'level' => 'debug',
                    'type' => 'single',
                    'max_file' => 30
                ]
            ];
        }

        $alipayConfig = self::getByGroup('alipay');

        $aliConfig = [];
        if ($payWayConfigCheck == PayFactory::ALIPAY) {
            foreach ($alipayConfig as $value) {
                if (empty($value)) {
                    throw new \Exception('请在后台配置支付宝支付, 后台->支付->支付宝支付');
                }
            }

            if (!file_exists(admin_public_path($alipayConfig['alipay_app_public_cert_path']))) {
                throw new \Exception('支付宝应用公钥证书配置不正确');
            }

            if (!file_exists(admin_public_path($alipayConfig['alipay_public_cert_path']))) {
                throw new \Exception('支付宝公钥证书配置不正确');
            }

            if (!file_exists(admin_public_path($alipayConfig['alipay_root_cert_path']))) {
                throw new \Exception('支付宝根证书配置不正确');
            }

            $aliConfig = [
                'app_id' => $alipayConfig['alipay_app_id'],
                'app_secret_cert' => $alipayConfig['alipay_app_secret'],
                'app_public_cert_path' => admin_public_path($alipayConfig['alipay_app_public_cert_path']),
                'alipay_public_cert_path' => admin_public_path($alipayConfig['alipay_public_cert_path']),
                'alipay_root_cert_path' => admin_public_path($alipayConfig['alipay_root_cert_path']),
                'notify_url' => getenv('APP_URL') . '/api/alipay/notify',
                'return_url' => '',
                'mode' => Pay::MODE_NORMAL,
                'log' => [
                    'file' => runtime_path().'/logs/alipay.log',
                    'level' => 'debug',
                    'type' => 'single',
                    'max_file' => 30
                ]
            ];
        }

        return [
            'wechat' => [
                'default' => $wechatConfig,
            ],
            'alipay' => [
                'default' => $aliConfig,
            ],
            'logger' => [
                'enable' => true,
                'file' => runtime_path().'/logs/payment.log',
                'level' => 'debug', // 建议生产环境等级调整为 info，开发环境为 debug
                'type' => 'single', // optional, 可选 daily.
                'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
            ],
            'http' => [ // optional
                'timeout' => 5.0,
                'connect_timeout' => 5.0,
                // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
            ],
            '_force' => true,
        ];
    }
}